<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
        <el-form-item label="服务站" prop="name">
         <el-input v-model="searchInfo.name" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="所属人姓名" prop="nickName">
         <el-input v-model="searchInfo.nickName" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="手机号" prop="phone">
         <el-input v-model="searchInfo.phone" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="省/市/区（县）" prop="province">
          <geo v-model:province="searchInfo.province" v-model:city="searchInfo.city" v-model:area="searchInfo.area"></geo>
        </el-form-item>
        <el-form-item label="详细地址" prop="addr">
         <el-input v-model="searchInfo.addr" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
        </div>
        <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID" @selection-change="handleSelectionChange" >
        <el-table-column align="left" label="服务站" prop="name" width="120" />
        <el-table-column align="left" label="所属人" prop="nickName" width="160" />
        <el-table-column align="left" label="手机号" prop="phone" width="120" />
        <el-table-column align="left" label="省/市/区(县)" prop="province" width="240">
          <template #default="{row}">
            <geo disabled v-model:province="row.province" v-model:city="row.city" v-model:area="row.area"></geo>
          </template>
        </el-table-column>
        <el-table-column align="left" label="详细地址" prop="addr" width="240" />
        <el-table-column align="left" label="创建日期" width="180">
          <template #default="scope">{{ formatDateYmd(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="left" label="启用" min-width="150" >
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              inline-prompt
              :active-value="1"
              :inactive-value="2"
              @change="()=>{switchEnable(scope.row)}"
            />
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作">
            <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                查看详情
            </el-button>
            <el-button type="primary" link icon="edit" class="table-button" @click="updateSysUserFunc(scope.row)">变更</el-button>
            <!-- <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button> -->
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
      <el-scrollbar height="500px">
          <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="160px">
            <el-form-item v-if="type==='create'" label="账号" prop="userName">
              <el-input v-model="formData.userName" />
            </el-form-item>
            <el-form-item v-if="type==='create'" label="密码" prop="password">
              <el-input v-model="formData.password" />
            </el-form-item>
            <el-form-item label="服务站名称:"  prop="name" >
              <el-input v-model="formData.name" :clearable="true"  placeholder="请输入" />
            </el-form-item>
            <el-form-item label="所属人姓名:"  prop="nickName" >
              <el-input v-model="formData.nickName" :clearable="true"  placeholder="请输入" />
            </el-form-item>
            <el-form-item label="手机号:"  prop="phone" >
              <el-input v-model="formData.phone" :clearable="true"  placeholder="请输入" />
            </el-form-item>
           
          
            <el-form-item label="省/市/区:"  prop="province" >
              <geo v-model:province="formData.province" v-model:city="formData.city" v-model:area="formData.area"></geo>
            </el-form-item>
            <el-form-item label="详细地址:"  prop="addr" >
              <el-input v-model="formData.addr" :clearable="true"  placeholder="请输入" />
            </el-form-item>
            <el-form-item label="启用" prop="disabled" >
              <el-switch
                v-model="formData.enable"
                inline-prompt
                :active-value="1"
                :inactive-value="2"
              />
            </el-form-item>
          </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="detailShow" style="width: 800px" lock-scroll :before-close="closeDetailShow" title="查看详情" destroy-on-close>
      <el-scrollbar height="550px">
        <el-descriptions column="1" border>
          <el-descriptions-item label="服务站名称">
              {{ formData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="所属人姓名">
              {{ formData.nickName }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
              {{ formData.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="省/市/区">
            <geo disabled v-model:province="formData.province" v-model:city="formData.city" v-model:area="formData.area"></geo>
          </el-descriptions-item>
          <el-descriptions-item label="详细地址">
              {{ formData.addr }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            {{ formStatus(formData.enable) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SysUser'
}
</script>

<script setup>
import {
  register,
  getSysUserInfoById,
  setUserInfo,
  setUserEnable,
  getHealthManageCenterList,
  deleteUser
} from '@/api/user'

import geo from '@/components/geo/geo.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatDateYmd, formStatus, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, ref, reactive } from 'vue'

// 自动化生成的字典（可能为空）以及字段

const formData = ref({
        name: '',
        nickName: '',
        authorityId:444,
        authorityIds:[444],
        phone: '',
        province: '',
        city: '',
        area: '',
        addr: '',
        })

// 验证规则
const rule = reactive({
               userName : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               password : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               name : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               nickName : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               phone : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               province : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               city : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               area : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               addr : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getHealthManageCenterList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteSysUserFunc(row)
        })
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateSysUserFunc = async(row) => {
    const res = await getSysUserInfoById({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data.sysUser
        dialogFormVisible.value = true
    }
}


// 删除行
const deleteSysUserFunc = async (row) => {
    const res = await deleteUser({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)


// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await getSysUserInfoById({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.sysUser
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
    name: '',
    nickName : '',
    phone: '',
    province: '',
    city: '',
    area: '',
    addr: '',
    authorityId:444,
    authorityIds:[444],
  }
}

// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
    nickName: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    addr: '',
    authorityId: 444,
    authorityIds:[444],
  }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
        if (!valid) return
          let res
          switch (type.value) {
            case 'create':
              res = await register(formData.value)
              break
            case 'update':
              res = await setUserInfo(formData.value)
              break
            default:
              res = await createSysUser(formData.value)
              break
          }
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '创建/更改成功'
            })
            closeDialog()
            getTableData()
          }
      })
}

const switchEnable = async(row) => {
  formData.value = JSON.parse(JSON.stringify(row))
  const req = {
    ...formData.value
  }
  const res = await setUserEnable(req)
  if (res.code === 0) {
    ElMessage({ type: 'success', message: `${req.enable === 2 ? '禁用' : '启用'}成功` })
    await getTableData()
  }
}

</script>

<style>

</style>
